package com.heima.search.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.AssociateDto;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.HistoryService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class HistoryServiceImpl implements HistoryService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Async
    public void save(Integer id, String searchWords) {
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("userId").is(id)
                        .and("keyword").is(searchWords))
                , ApUserSearch.class);
        //判断数据是否存在
        if(CollectionUtils.isNotEmpty(apUserSearches)){
            ApUserSearch apUserSearch = apUserSearches.get(0);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //判断是否超过十条
        List<ApUserSearch> searhes = mongoTemplate.find(Query.query(Criteria.where("userId").is(id))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);

        if(searhes.size() >= 10){
            //超过十条
            ApUserSearch apUserSearch = searhes.get(searhes.size() - 1);
            apUserSearch.setKeyword(searchWords);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        }else {
            //未超过
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setUserId(id);
            apUserSearch.setKeyword(searchWords);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        }
    }

    @Override
    public List<ApUserSearch> load() {

        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("userId").is(AppThreadLocalUtil.getUser().getId()))
                .with(Sort.by(Sort.Direction.DESC, "createTime")), ApUserSearch.class);

        return apUserSearches;
    }

    @Override
    public void del(HistorySearchDto dto) {
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer id = user.getId();

        mongoTemplate.remove(Query.query(Criteria.where("_id").is(dto.getId())
                .and("userId").is(id)),ApUserSearch.class);

    }

    @Override
    public List<ApAssociateWords> search(AssociateDto dto) {
        List<ApAssociateWords> associateWords = mongoTemplate.find(Query.query(Criteria.where("associateWords")
                        .regex(".*" + dto.getSearchWords() + ".*")).limit(dto.getPageSize()), ApAssociateWords.class);
        return associateWords;
    }
}
